package com.eva.captcha.service;

import com.eva.framework.cache.CacheProxy;
import com.eva.framework.captcha.model.ImageCaptcha;
import com.eva.framework.captcha.service.ImageCaptchaService;
import com.eva.framework.common.constants.ResponseStatus;
import com.eva.framework.common.exception.BusinessException;
import com.eva.framework.config.AppConfig;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ImageCaptchaServiceImpl implements ImageCaptchaService {

    @Resource
    private AppConfig appConfig;

    @Resource
    private CacheProxy<String, String> cacheProxy;

    @Override
    public ImageCaptcha genCaptcha() {
        ImageCaptcha captcha = ImageCaptchaService.super.genCaptcha();
        // 写入缓存
        cacheProxy.put(captcha.getUuid(), captcha.getText(), appConfig.getCaptcha().getImage().getExpire());
        return captcha;
    }

    @Override
    public void check(String uuid, String code) {
        // 测试模式下不校验
        if (appConfig.isTestingMode()) {
            return;
        }
        String cacheCode = cacheProxy.get(uuid);
        if (cacheCode == null) {
            throw new BusinessException(ResponseStatus.VERIFICATION_CODE_INCORRECT);
        }
        cacheProxy.remove(cacheCode);
        if (!code.equalsIgnoreCase(cacheCode)) {
            throw new BusinessException(ResponseStatus.VERIFICATION_CODE_INCORRECT);
        }
    }
}
